import thin_render from "../../lib/thin_render.mjs";
import thin_rerender from "../../lib/thin_rerender.mjs";
import datarover from "../../lib/datarover.mjs";
import collectdata from "../../lib/collectdata.mjs";
import { nearest_querycontainer } from "../../lib/nearest.mjs";

/**
 * 渲染过滤器行
 * @param {HTMLElement} thead - 表头容器元素
 * @param {Object} template - 模板配置对象
 * @param {HTMLElement} headerrow - 表头行元素，用于参考定位
 * @param {function} onFilter - 过滤器变化时的回调函数
 */
export function renderFilter(thead, template, headerrow, onFilter) {
  // 检查是否需要渲染过滤器
  if (template.gridview?.find((col) => col.filter !== undefined)) {
    let filterrow = document.createElement("tr");
    thead.appendChild(filterrow);

    // 创建过滤器处理函数（闭包中可以访问 filterrow）
    function filter_handler(ev) {
      let filter = {};
      let d = collectdata(filterrow);
      // 收集非空的过滤值
      for (let key in d) {
        if (d[key] !== "") {
          filter[key] = d[key];
        }
      }

      if (onFilter) {
        // 使用传入的过滤处理函数
        onFilter({ filter: filter });
      } else {
        // 使用默认的查询过滤
        let querycontainer = nearest_querycontainer(ev.sender);
        querycontainer.thin_query.filter = filter;
        querycontainer.thin_query.pagenum = 1;
        thin_rerender(querycontainer);
      }
    }

    template.gridview.forEach((col) => {
      let td = document.createElement("td");
      filterrow.appendChild(td);
      if (col.class) {
        td.setAttribute("class", col.class);
      }

      // 根据过滤器类型渲染不同的控件
      if (col.filter === undefined) {
      } else if (col.filter.input) {
        // 渲染输入框过滤器
        thin_render(td, {
          input: col.filter.input,
          type: col.filter.type,
          value: "[[filter/" + col.filter.input + "]]",
          event: { change: col.filter.event?.change || filter_handler },
        });
      } else if (col.filter.select) {
        if (col.filter.datapath) {
          // 从数据路径获取选项的下拉框
          let options =
            col.filter.emptyforall === true
              ? [""].concat(datarover(td, col.filter.datapath))
              : datarover(td, col.filter.datapath);
          thin_render(td, {
            select: col.filter.select,
            value: "[[filter/" + col.filter.select + "]]",
            options: options,
            event: { change: col.filter.event?.change || filter_handler },
          });
        } else if (col.filter.ajax) {
          // 从AJAX获取选项的下拉框
          thin_render(td, {
            select: col.filter.select,
            value: "[[filter/" + col.filter.select + "]]",
            ajax: col.filter.ajax,
            event: { change: col.filter.event?.change || filter_handler },
          });
        } else {
          // 静态选项的下拉框
          thin_render(td, {
            select: col.filter.select,
            value: "[[filter/" + col.filter.select + "]]",
            options: col.filter.options,
            event: { change: col.filter.event?.change || filter_handler },
          });
        }
      } else {
        // 自定义过滤器
        thin_render(td, col.filter);
        td.addEventListener("change", (ev) => {
          if (!ev.target.classList.contains("selectall")) {
            filter_handler({ sender: ev.target, event: ev });
          }
        });
      }
    });
  }
}
